package cn.xiaoyuan.controller.api;

import cn.xiaoyuan.entity.AuthUser;
import cn.xiaoyuan.service.UserAuthService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RequestMapping("/api/auth")
@Controller
public class AuthApiController {
    @Resource
    UserAuthService userAuthService;

    @RequestMapping("/dologin")
    public String dologin(String username, String password, String role, Model model,HttpSession session) {
        AuthUser authUser = userAuthService.getAuthUserByName(username);
        if (username == null || username.equals("") || password == null || password.equals("") || role == null) {
            model.addAttribute("mes", "您输入的不对");
            return "forward:/page/auth/login";
        }
        if (authUser == null) {
            model.addAttribute("mes", "请先注册");
            return "forward:/page/auth/login";
        }
        if (!authUser.getPassword().equals(password)) {
            model.addAttribute("mes", "您输入的密码不对");
            return "forward:/page/auth/login";
        }
        if(authUser.getState().equals("封禁")){
            model.addAttribute("mes", "您的账号被封禁");
            return "forward:/page/auth/login";
        }
        session.setAttribute("user", authUser);
        String roleName=userAuthService.getRoleNameByRoleId(authUser.getRoleId());
        session.setAttribute("role",roleName);
        return "redirect:/page/auth/index";
    }

    @Transactional
    @RequestMapping("/enroll")
    public String enroll(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("role") String role, @RequestParam("realname") String realname, @RequestParam(value = "tel", required = false) String tel, Model model) {
        if(username.equals(userAuthService.getAuthUserByName(username).getUsername())){
            model.addAttribute("mes","该用户已经被注册");
            return "redirect:/page/auth/login";
        }
        if(tel.equals(userAuthService.getTel(tel))){
            model.addAttribute("mes","该手机号已经被注册");
            return "redirect:/page/auth/login";
        }
       if(!(role.equals("user") || role.equals("vistor"))){
           model.addAttribute("mes","您的身份提交的不符合");
            return "redirect:/page/auth/login";
        }
        Integer roleId = userAuthService.getRoleIdByName(role);
        userAuthService.register(username, password, roleId, realname, tel);
        return "redirect:/page/auth/login";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
//        session.removeAttribute("user");
        session.invalidate();
        return "redirect:/page/auth/login";
    }
}
